package com.elite.groovy.callback

import com.elite.groovy.util.EliteBean
import com.elite.groovy.util.Util
import net.sf.json.JSONObject
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

public class sendSmsTaskNew implements ServiceBackInvoke  {
    private static final Log log = LogFactory.getLog(sendSmsTaskNew.class);
    private String charset = "gbk"; //设置字符集
    private int timeout = 100000; //设置请求超时时间
    private int enableSSLflag = 1;

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response){
        def list = eliteBean.chaxun_sqlRowSet("select documentout_guid,documentpath,documentto,model_id,parameter from documentout where doctype=3 and status=0 and trialcountlimit>trialcount and sysdate>expectedstartdate and (sub_doctype<>'myd' or sub_doctype is null)", "dataSource");
        def smap = eliteBean.chaxun_sql("select url,th_code,dd_key,dd_use_id,edj_appkey from sysc_interface where urltype ='newsmsSend'", "dataSource");
        if (smap.size() == 0) {
            return
        };
        String url = smap[0].getAt("url");
        String appCode = smap[0].getAt("th_code");//账号编码
        String appSecret = smap[0].getAt("dd_key");//账号密码
        String bizType = smap[0].getAt("dd_use_id");//业务类型
        String orgCode = smap[0].getAt("edj_appkey");//机构代码
        int i = 0;
        while (list.next()) {
            try {
                i++;
                def documentoutGuid = list.getString(1); //获取待发送短信guid
                def content = list.getString(2); //获取短信内容
                def mobile = list.getString(3); //获取短信号码
                def modelId = Util.filterForObject(list.getString(4)); //获取模板ID
                def paramsMap = list.getString(5); //获取短信模板参数
                if (modelId.equals("")) {
                    noModelSend(eliteBean, documentoutGuid, url, mobile, content, appCode, appSecret, bizType, orgCode);
                } else {
                    hasModelSend(eliteBean,documentoutGuid,url,mobile,modelId,paramsMap,appCode,appSecret,bizType,orgCode);
                }
            } catch (Exception e) {
                log.error("ErrorMessage:", e);
            }
        };
        log.debug("本次发送短信" + i + "条");
    }

    //无模板短信发送
    public boolean noModelSend(EliteBean eliteBean, String msgGuid, String url, String mobile, String content, String appCode, String appSecret, String bizType, String orgCode) throws Exception {
        try {
            HashMap<String, Object> headMap = new HashMap<>();
            headMap.put("Content-Type", "application/json");
            JSONObject smsJson = new JSONObject();
            smsJson.put("appCode", appCode);
            smsJson.put("appSecret", appSecret);
            smsJson.put("mobile", mobile);
            smsJson.put("content", URLEncoder.encode(content, "UTF-8"));
            smsJson.put("isIm", 1);
            smsJson.put("chanType", 2);
            smsJson.put("orgCode", orgCode);
            smsJson.put("bizType", bizType);
            String httpresult = Util.doHttpPostUseHead(url, smsJson.toString(), charset, timeout, enableSSLflag, headMap);
            JSONObject obj = JSONObject.fromObject(httpresult);
			log.debug("obj:"+obj);
            String msgId=obj.getString("smsId");
            if (obj.get("result") == 0) {
                msgSendStatus(eliteBean, 1, "", obj.getString("smsId"), msgGuid);
                return true;
            } else {
                msgSendStatus(eliteBean, 5, obj.getString("message"), obj.getString("smsId"), msgGuid);
                return false;

            }
        } catch (Exception e) {
            log.error("ErrorMessage:", e);
            msgSendStatus(eliteBean, 5, "调用短信接口异常", '', msgGuid)
            return false
        }

    }


    //又模板短信发送
    public boolean hasModelSend(EliteBean eliteBean, String msgGuid, String url, String mobile, String modelId,String paramsMap8, String appCode, String appSecret, String bizType, String orgCode) throws Exception {
        try {
            HashMap<String, Object> headMap = new HashMap<>();
            headMap.put("Content-Type", "application/json");
            JSONObject smsJson = new JSONObject();
            smsJson.put("appCode", appCode);
            smsJson.put("appSecret", appSecret);
            smsJson.put("mobile", mobile);
            smsJson.put("tmplCode", modelId);
            smsJson.put("tmplParam", paramsMap8);
            //smsJson.put("content", URLEncoder.encode(content, "UTF-8"));
            smsJson.put("isIm", 0);
            smsJson.put("chanType", 2);
            smsJson.put("orgCode", orgCode);
            smsJson.put("bizType", bizType);
            String httpresult = Util.doHttpPostUseHead(url, smsJson.toString(), charset, timeout, enableSSLflag, headMap);
            JSONObject obj = JSONObject.fromObject(httpresult);
            String msgId=obj.getString("smsId");
            if (obj.get("result") == 0) {
                msgSendStatus(eliteBean, 1, "", obj.getString("smsId"), msgGuid);
                return true;
            } else {
                msgSendStatus(eliteBean, 5, obj.getString("message"), obj.getString("smsId"), msgGuid);
                return false;

            }
        } catch (Exception e) {
            log.error("ErrorMessage:", e);
            msgSendStatus(eliteBean, 5, "调用短信接口异常", '', msgGuid)
            return false
        }

    }
    /**
     *
     * @use 短信发送状态更新* @param eliteBean
     * @param msgStatus 1已发送  5发送失败
     * @param errorMsg 失败原因
     * @param msgId 提交到短信平台的短信ID
     * @param msgGuid documentout_guid
     * @return
     * @throws Exception
     */
    private static boolean msgSendStatus(EliteBean eliteBean, int msgStatus, String errorMsg, String msgId, String msgGuid) throws Exception {
        try {
            MapSqlParameterSource params = new MapSqlParameterSource(); //sql防注入方式
            params.addValue("errorMsg", errorMsg);
            params.addValue("msgId", msgId);
            params.addValue("msgGuid", msgGuid);
            if (msgStatus == 1) {
                eliteBean.update_sql_pro("update documentout set msgid=:msgId,status=1,TRIALCOUNT=TRIALCOUNT+1,LASTTRYDATETIME=sysdate,MODIFIEDDATE=sysdate,MODIFIEDBY='SELITE' WHERE documentout_guid=:msgGuid", params, "dataSource");
            } else if (msgStatus == 5) {
                eliteBean.update_sql_pro("update documentout set msgid=:msgId,Status= case when TRIALCOUNT+1=TRIALCOUNTLIMIT then 5 else Status end,FAILDESCRIPTION=:errorMsg,TRIALCOUNT=TRIALCOUNT+1,LASTTRYDATETIME=sysdate,MODIFIEDDATE=sysdate,MODIFIEDBY='SELITE' WHERE documentout_guid=:msgGuid", params, "dataSource");
            };
            return true
        } catch (Exception e) {
            log.error("ErrorMessage:", e);
            return false
        }
    }


}
